package com.cynteka.cyfoman.ui.bind;

import com.cynteka.cyfoman.core.ValueObject;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.awt.*;
import java.util.List;

/**
 * User: Sergey
 * Date: 10.08.11
 * Time: 18:49
 */
public class FormBinder {

    private static final List<ComponentBeanBinder> DEFAULT_BINDERS = Arrays.asList(new ComponentBeanBinder[] {
            new TextFieldBinder(),
    });

    public List<ComponentBeanBinder> getBinders() {
        return binders;
    }

    public void setBinders(List<ComponentBeanBinder> binders) {
        this.binders = binders;
    }

    private List<ComponentBeanBinder> binders = DEFAULT_BINDERS;

    public void bind(ValueObject bean, Object form) {
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(form.getClass());
        for(PropertyDescriptor descriptor : descriptors) {
            Method m = descriptor.getReadMethod();
            if(m != null) {
                try {
                    Object component = m.invoke(form);
                    for(ComponentBeanBinder binder : binders) {
                        if(binder.bind(bean, component, descriptor.getName())) {
                            break;
                        }
                    }
                } catch (IllegalAccessException e) {
                    // TODO log it
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                } catch (InvocationTargetException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }

    }

}
